home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / programr / fileutil.zip / CUT.C < prev    next >
C/C++ Source or Header  |  1992-02-22  |  17KB  |  648 lines

  1. /* cut - remove parts of lines of files
  2.    Copyright (C) 1984 by David M. Ihnat
  3.  
  4.    This program is a total rewrite of the Bell Laboratories Unix(Tm)
  5.    command of the same name, as of System V.  It contains no proprietary
  6.    code, and therefore may be used without violation of any proprietary
  7.    agreements whatsoever.  However, you will notice that the program is
  8.    copyrighted by me.  This is to assure the program does *not* fall
  9.    into the public domain.  Thus, I may specify just what I am now:
  10.    This program may be freely copied and distributed, provided this notice
  11.    remains; it may not be sold for profit without express written consent of
  12.    the author.
  13.    Please note that I recreated the behavior of the Unix(Tm) 'cut' command
  14.    as faithfully as possible; however, I haven't run a full set of regression
  15.    tests.  Thus, the user of this program accepts full responsibility for any
  16.    effects or loss; in particular, the author is not responsible for any losses,
  17.    explicit or incidental, that may be incurred through use of this program.
  18.  
  19.    I ask that any bugs (and, if possible, fixes) be reported to me when
  20.    possible.  -David Ihnat (312) 784-4544 ignatz@homebru.chi.il.us
  21.  
  22.    POSIX changes, bug fixes, long-named options, and cleanup
  23.    by David MacKenzie <djm@ai.mit.edu>.
  24.  
  25.    Usage: cut {-b byte-list,+bytes byte-list} [-n] [file...]
  26.           cut {-c character-list,+characters character-list} [file...]
  27.           cut {-f field-list,+fields field-list} [-d delim] [-s]
  28.           [+delimiter delim] [+only-delimited] [file...]
  29.  
  30.    Options:
  31.    +bytes byte-list
  32.    -b byte-list            Print only the bytes in positions listed
  33.                 in BYTE-LIST.
  34.                 Tabs and backspaces are treated like any
  35.                 other character; they take up 1 byte.
  36.  
  37.    +characters character-list
  38.    -c character-list        Print only characters in positions listed
  39.                 in CHARACTER-LIST.
  40.                 The same as -b for now, but
  41.                 internationalization will change that.
  42.                 Tabs and backspaces are treated like any
  43.                 other character; they take up 1 character.
  44.  
  45.    +fields field-list
  46.    -f field-list        Print only the fields listed in FIELD-LIST.
  47.                 Fields are separated by a TAB by default.
  48.  
  49.    +delimiter delim
  50.    -d delim            For -f, fields are separated by the first
  51.                 character in DELIM instead of TAB.
  52.  
  53.    -n                Do not split multibyte chars (no-op for now).
  54.  
  55.    +only-delimited
  56.    -s                For -f, do not print lines that do not contain
  57.                 the field separator character.
  58.  
  59.    The BYTE-LIST, CHARACTER-LIST, and FIELD-LIST are one or more numbers
  60.    or ranges separated by commas.  The first byte, character, and field
  61.    are numbered 1.
  62.  
  63.    A FILE of `-' means standard input. */
  64.  
  65. /* MS-DOS port (c) 1990 by Thorsten Ohl, ohl@gnu.ai.mit.edu
  66.    This port is also distributed under the terms of the
  67.    GNU General Public License as published by the
  68.    Free Software Foundation.
  69.  
  70.    Please note that this file is not identical to the
  71.    original GNU release, you should have received this
  72.    code as patch to the official release.  */
  73.  
  74. #ifdef MSDOS
  75. static char RCS_Id[] =
  76.   "$Header: e:/gnu/fileutil/RCS/cut.c 1.4.0.3 90/09/19 11:17:49 tho Exp $";
  77.  
  78. static char Program_Id[] = "cut";
  79. static char RCS_Revision[] = "$Revision: 1.4.0.3 $";
  80.  
  81. #define VERSION \
  82.   "GNU %s, Version %.*s (compiled %s %s for MS-DOS)\n", Program_Id, \
  83.   (sizeof RCS_Revision - 14), (RCS_Revision + 11), __DATE__, __TIME__
  84.  
  85. #define COPYING \
  86.   "This is free software, distributed under the terms of the\n" \
  87.   "GNU General Public License.  For details, see the file COPYING.\n"
  88. #endif /* MSDOS */
  89.  
  90. #include <stdio.h>
  91. #include <errno.h>
  92. #include <getopt.h>
  93. #include <sys/types.h>
  94. #include "system.h"
  95.  
  96. #ifdef STDC_HEADERS
  97. #include <stdlib.h>
  98. #else
  99. char *malloc ();
  100. char *realloc ();
  101. void exit ();
  102.  
  103. extern int errno;
  104. #endif
  105.  
  106. #ifdef MSDOS
  107.  
  108. #include <gnulib.h>
  109.  
  110. void main (int argc, char **argv);
  111. int set_fields (char *fieldstr);
  112. void cut_file (FILE * stream);
  113. void cut_file_bytes (FILE * fno);
  114. void cut_file_fields (FILE * fno);
  115. void enlarge_line (int new_size);
  116. void invalid_list (void);
  117. void usage (void);
  118.  
  119. #else /* not MSDOS */
  120.  
  121. char *xmalloc ();
  122. char *xrealloc ();
  123. int set_fields ();
  124. void cut_file ();
  125. void cut_file_bytes ();
  126. void cut_file_fields ();
  127. void enlarge_line ();
  128. void error ();
  129. void invalid_list ();
  130. void usage ();
  131.  
  132. #endif /* not MSDOS */
  133.  
  134. /* The number of elements allocated for the input line
  135.    and the byte or field number.
  136.    Enlarged as necessary. */
  137. int line_size;
  138.  
  139. /* Processed output buffer. */
  140. char *outbuf;
  141.  
  142. /* Raw line buffer for field mode. */
  143. char *inbuf;
  144.  
  145. /* What can be done about a byte or field. */
  146. enum field_action
  147. {
  148.   field_omit,
  149.   field_output
  150. };
  151.  
  152. /* In byte mode, which bytes to output.
  153.    In field mode, which `delim'-separated fields to output.
  154.    Both bytes and fields are numbered starting with 1,
  155.    so the first element of `fields' is unused. */
  156. enum field_action *fields;
  157.  
  158. enum operating_mode
  159. {
  160.   undefined_mode,
  161.  
  162.   /* Output characters that are in the given bytes. */
  163.   byte_mode,
  164.  
  165.   /* Output the given delimeter-separated fields. */
  166.   field_mode
  167. };
  168.  
  169. enum operating_mode operating_mode;
  170.  
  171. /* If nonzero,
  172.    for field mode, do not output lines containing no delimeter characters. */
  173. int delimited_lines_only;
  174.  
  175. /* The delimeter character for field mode. */
  176. unsigned char delim;
  177.  
  178. /* The name this program was run with. */
  179. char *program_name;
  180.  
  181. struct option longopts[] =
  182. {
  183. #ifdef MSDOS
  184.   {"copying", 0, NULL, 30},
  185.   {"version", 0, NULL, 31},
  186. #endif
  187.   {"bytes", 1, 0, 'b'},
  188.   {"characters", 1, 0, 'c'},
  189.   {"fields", 1, 0, 'f'},
  190.   {"delimiter", 0, 0, 'd'},
  191.   {"only-delimited", 0, 0, 's'},
  192.   {0, 0, 0, 0}
  193. };
  194.  
  195. void
  196. main (argc, argv)
  197.      int argc;
  198.      char **argv;
  199. {
  200.   FILE *fileptr;
  201.   int optc;
  202.   int longind;
  203.   int exit_status = 0;
  204.  
  205.   program_name = argv[0];
  206.  
  207.   line_size = 512;
  208.   operating_mode = undefined_mode;
  209.   delimited_lines_only = 0;
  210.   delim = '\0';
  211.  
  212.   fields = (enum field_action *)
  213.     xmalloc (line_size * sizeof (enum field_action));
  214.   outbuf = (char *) xmalloc (line_size);
  215.   inbuf = (char *) xmalloc (line_size);
  216.  
  217.   for (optc = 0; optc < line_size; optc++)
  218.     fields[optc] = field_omit;
  219.  
  220.   while ((optc = getopt_long (argc, argv, "b:c:d:f:ns", longopts, &longind))
  221.      != EOF)
  222.     {
  223.       switch (optc)
  224.     {
  225.     case 'b':
  226.     case 'c':
  227.       /* Build the byte list. */
  228.       if (operating_mode != undefined_mode)
  229.         usage ();
  230.       operating_mode = byte_mode;
  231.       if (set_fields (optarg) == 0)
  232.         error (2, 0, "no fields given");
  233.       break;
  234.  
  235.     case 'f':
  236.       /* Build the field list. */
  237.       if (operating_mode != undefined_mode)
  238.         usage ();
  239.       operating_mode = field_mode;
  240.       if (set_fields (optarg) == 0)
  241.         error (2, 0, "no fields given");
  242.       break;
  243.  
  244.     case 'd':
  245.       /* New delimiter. */
  246.       if (optarg[0] == '\0')
  247.         error (2, 0, "no delimiter given");
  248.       if (optarg[1] != '\0')
  249.         error (2, 0, "delimiter must be a single character");
  250.       delim = optarg[0];
  251.       break;
  252.  
  253.     case 'n':
  254.       break;
  255.  
  256.     case 's':
  257.       delimited_lines_only++;
  258.       break;
  259.  
  260. #ifdef MSDOS
  261.     case 30:
  262.       fprintf (stderr, COPYING);
  263.       exit (0);
  264.       break;
  265.  
  266.     case 31:
  267.       fprintf (stderr, VERSION);
  268.       exit (0);
  269.       break;
  270. #endif
  271.  
  272.     default:
  273.       usage ();
  274.     }
  275.     }
  276.  
  277.   if (operating_mode == undefined_mode)
  278.     usage ();
  279.  
  280.   if ((delimited_lines_only || delim != '\0') && operating_mode != field_mode)
  281.     usage ();
  282.  
  283.   if (delim == '\0')
  284.     delim = '\t';
  285.  
  286.   if (optind == argc)
  287.     cut_file (stdin);
  288.   else
  289.     for (; optind < argc; optind++)
  290.       {
  291.     if (!strcmp (argv[optind], "-"))
  292.       cut_file (stdin);
  293.     else
  294.       {
  295.         fileptr = fopen (argv[optind], "r");
  296.         if (fileptr == NULL)
  297.           {
  298.         error (0, errno, "%s", argv[optind]);
  299.         exit_status = 1;
  300.           }
  301.         else
  302.           {
  303.         cut_file (fileptr);
  304.         fclose (fileptr);
  305.           }
  306.       }
  307.       }
  308.  
  309.   exit (exit_status);
  310. }
  311.  
  312. /* Select for printing the positions in `fields' that are listed in
  313.    byte or field specification FIELDSTR.  FIELDSTR should be
  314.    composed of one or more numbers or ranges of numbers, separated by
  315.    blanks or commas.  Incomplete ranges may be given: `-m' means
  316.    `1-m'; `n-' means `n' through end of line or last field.
  317.  
  318.    Return the number of fields selected. */
  319.  
  320. int
  321. set_fields (fieldstr)
  322.      char *fieldstr;
  323. {
  324.   int initial = 1;        /* Value of first number in a range. */
  325.   int dash_found = 0;        /* Nonzero if a '-' is found in this field. */
  326.   int value = 0;        /* If nonzero, a number being accumulated. */
  327.   int fieldset = 0;        /* Number of fields selected so far. */
  328.   /* If nonzero, index of first field in a range that goes to end of line. */
  329.   int eol_range_start = 0;
  330.  
  331.   for (;;)
  332.     {
  333.       switch (*fieldstr)
  334.     {
  335.     case '-':
  336.       /* Starting a range. */
  337.       if (dash_found)
  338.         invalid_list ();
  339.       dash_found++;
  340.       fieldstr++;
  341.  
  342.       if (value)
  343.         {
  344.           if (value >= line_size)
  345.         enlarge_line (value);
  346.           initial = value;
  347.           value = 0;
  348.         }
  349.       else
  350.         initial = 1;
  351.       break;
  352.  
  353.     case ',':
  354.     case '\0':
  355.       /* Ending the string, or this field/byte sublist. */
  356.       if (dash_found)
  357.         {
  358.           dash_found = 0;
  359.  
  360.           /* A range.  Possibilites: -n, m-n, n-.
  361.          In any case, `initial' contains the start of the range. */
  362.           if (value == 0)
  363.         {
  364.           /* `n-'.  From `initial' to end of line. */
  365.           eol_range_start = initial;
  366.           fieldset++;
  367.         }
  368.           else
  369.         {
  370.           /* `m-n' or `-n' (1-n). */
  371.           if (value < initial)
  372.             invalid_list ();
  373.  
  374.           if (value >= line_size)
  375.             enlarge_line (value);
  376.  
  377.           /* Is there already a range going to end of line? */
  378.           if (eol_range_start != 0)
  379.             {
  380.               /* Yes.  Is the new sequence already contained
  381.              in the old one?  If so, no processing is
  382.              necessary. */
  383.               if (initial < eol_range_start)
  384.             {
  385.               /* No, the new sequence starts before the
  386.                  old.  Does the old range going to end of line
  387.                  extend into the new range?  */
  388.               if (eol_range_start < value)
  389.                 /* Yes.  Simply move the end of line marker. */
  390.                 eol_range_start = initial;
  391.               else
  392.                 /* No.  A simple range, before and disjoint from
  393.                    the range going to end of line.  Fill it. */
  394.                 for (; initial <= value; initial++)
  395.                   fields[initial] = field_output;
  396.  
  397.               /* In any case, some fields were selected. */
  398.               fieldset++;
  399.             }
  400.             }
  401.           else
  402.             {
  403.               /* There is no range going to end of line. */
  404.               for (; initial <= value; initial++)
  405.             fields[initial] = field_output;
  406.               fieldset++;
  407.             }
  408.           value = 0;
  409.         }
  410.         }
  411.       else if (value != 0)
  412.         {
  413.           /* A simple field number, not a range. */
  414.           if (value >= line_size)
  415.         enlarge_line (value);
  416.  
  417.           fields[value] = field_output;
  418.           value = 0;
  419.           fieldset++;
  420.         }
  421.  
  422.       if (*fieldstr == '\0')
  423.         {
  424.           /* If there was a range going to end of line, fill the
  425.          array from the end of line point.  */
  426.           if (eol_range_start)
  427.         for (initial = eol_range_start; initial < line_size; initial++)
  428.           fields[initial] = field_output;
  429.  
  430.           return fieldset;
  431.         }
  432.  
  433.       fieldstr++;
  434.       break;
  435.  
  436.     default:
  437.       if (*fieldstr < '0' || *fieldstr > '9')
  438.         invalid_list ();
  439.  
  440.       value = 10 * value + *fieldstr - '0';
  441.       fieldstr++;
  442.       break;
  443.     }
  444.     }
  445. }
  446.  
  447. void
  448. cut_file (stream)
  449.      FILE *stream;
  450. {
  451.   if (operating_mode == byte_mode)
  452.     cut_file_bytes (stream);
  453.   else
  454.     cut_file_fields (stream);
  455. }
  456.  
  457. /* Print the file open for reading on stream FNO
  458.    with the bytes specified in `fields' removed from each line. */
  459.  
  460. void
  461. cut_file_bytes (fno)
  462.      FILE *fno;
  463. {
  464.   register int c;        /* Each character from the file. */
  465.   int doneflag = 0;        /* Nonzero if EOF reached. */
  466.   int char_count;        /* Number of chars in the line so far. */
  467.   char *outbufptr;        /* Where to save next char to output. */
  468.  
  469.   while (doneflag == 0)
  470.     {
  471.       /* Start processing a line. */
  472.       outbufptr = outbuf;
  473.       char_count = 0;
  474.  
  475.       do
  476.     {
  477.       c = getc (fno);
  478.       if (c == EOF)
  479.         {
  480.           doneflag++;
  481.           break;
  482.         }
  483.  
  484.       /* If this character is to be sent, stow it in the outbuffer. */
  485.  
  486.       if (++char_count == line_size - 1)
  487.         enlarge_line (char_count);
  488.           
  489.       if (fields[char_count] == field_output || c == '\n')
  490.         *outbufptr++ = c;
  491.     }
  492.       while (c != '\n');
  493.       
  494.       if (char_count)
  495.     fwrite (outbuf, sizeof (char), outbufptr - outbuf, stdout);
  496.     }
  497. }
  498.  
  499. /* Print the file open for reading on stream FNO
  500.    with the fields specified in `fields' removed from each line.
  501.    All characters are initially stowed in the raw input buffer, until
  502.    at least one field has been found. */
  503.  
  504. void
  505. cut_file_fields (fno)
  506.      FILE *fno;
  507. {
  508.   register int c;        /* Each character from the file. */
  509.   int doneflag = 0;        /* Nonzero if EOF reached. */
  510.   int char_count;        /* Number of chars in line before any delim. */
  511.   int fieldfound;        /* Nonzero if any fields to print found. */
  512.   int curr_field;        /* Current index in `fields'. */
  513.   char *outbufptr;        /* Where to save next char to output. */
  514.   char *inbufptr;        /* Where to save next input char. */
  515.  
  516.   while (doneflag == 0)
  517.     {
  518.       char_count = 0;
  519.       fieldfound = 0;
  520.       curr_field = 1;
  521.       outbufptr = outbuf;
  522.       inbufptr = inbuf;
  523.  
  524.       do
  525.     {
  526.       c = getc (fno);
  527.       if (c == EOF)
  528.         {
  529.           doneflag++;
  530.           break;
  531.         }
  532.  
  533.       if (fields[curr_field] == field_output && c != '\n')
  534.         {
  535.           /* Working on a field.  It, and its terminating
  536.          delimiter, go only into the processed buffer. */
  537.           fieldfound = 1;
  538.           if (outbufptr - outbuf == line_size - 2)
  539.         enlarge_line (outbufptr - outbuf);
  540.           *outbufptr++ = c;
  541.         }
  542.       else if (fieldfound == 0)
  543.         {
  544.           if (++char_count == line_size - 1)
  545.         enlarge_line (char_count);
  546.           *inbufptr++ = c;
  547.         }
  548.  
  549.       if (c == delim && ++curr_field == line_size - 1)
  550.         enlarge_line (curr_field);
  551.     }
  552.       while (c != '\n');
  553.  
  554.       if (fieldfound)
  555.     {
  556.       /* Something was found. Print it. */
  557.       if (outbufptr[-1] == delim)
  558.         --outbufptr;    /* Supress trailing delimiter. */
  559.  
  560.       fwrite (outbuf, sizeof (char), outbufptr - outbuf, stdout);
  561.       if (c == '\n')
  562.         putc (c, stdout);
  563.     }
  564.       else if (!delimited_lines_only && char_count)
  565.     /* A line with some characters, no delimiters, and no
  566.        supression.  Print it. */
  567.     fwrite (inbuf, sizeof (char), inbufptr - inbuf, stdout);
  568.     }
  569. }
  570.  
  571. /* Extend the buffers to accomodate at least NEW_SIZE characters. */
  572.  
  573. void
  574. enlarge_line (new_size)
  575.      int new_size;
  576. {
  577.   int i;
  578.  
  579.   new_size += 256;        /* Leave some room to grow. */
  580.   fields = (enum field_action *)
  581.     xrealloc (fields, new_size * sizeof (enum field_action));
  582.   outbuf = (char *) xrealloc (outbuf, new_size);
  583.   inbuf = (char *) xrealloc (inbuf, new_size);
  584.   for (i = line_size; i < new_size; i++)
  585.     fields[i] = field_omit;
  586.   line_size = new_size;
  587. }
  588.  
  589.  
  590. #ifndef MSDOS            /* We have it in gnulib  */
  591.  
  592. /* Allocate N bytes of memory dynamically, with error checking.  */
  593.  
  594. char *
  595. xmalloc (n)
  596.      unsigned n;
  597. {
  598.   char *p;
  599.  
  600.   p = malloc (n);
  601.   if (p == 0)
  602.     error (2, 0, "virtual memory exhausted");
  603.   return p;
  604. }
  605.  
  606. char *
  607. xrealloc (p, n)
  608.      char *p;
  609.      unsigned n;
  610. {
  611.   p = realloc (p, n);
  612.   if (p == 0)
  613.     error (2, 0, "virtual memory exhausted");
  614.   return p;
  615. }
  616.  
  617. #endif /* not MSDOS */
  618.  
  619. void
  620. invalid_list ()
  621. {
  622.   error (2, 0, "invalid byte or field list");
  623. }
  624.  
  625. void
  626. usage ()
  627. {
  628.  
  629. #ifdef MSDOS
  630.   fprintf (stderr, "\
  631. Usage: %s {-b byte-list,+bytes byte-list} [-n] [+copying]\n\
  632.        [+version] [file...]\n\
  633.        %s {-c character-list,+characters character-list} [+copying]\n\
  634.        [+version] [file...]\n\
  635.        %s {-f field-list,+fields field-list} [-d delim] [-s]\n\
  636.        [+delimiter delim] [+only-delimited] [+copying] [+version] [file...]\n",
  637.        program_name, program_name, program_name);
  638. #else /* not MSDOS */
  639.   fprintf (stderr, "\
  640. Usage: %s {-b byte-list,+bytes byte-list} [-n] [file...]\n\
  641.        %s {-c character-list,+characters character-list} [file...]\n\
  642.        %s {-f field-list,+fields field-list} [-d delim] [-s]\n\
  643.        [+delimiter delim] [+only-delimited] [file...]\n",
  644.        program_name, program_name, program_name);
  645. #endif /* not MSDOS */
  646.   exit (2);
  647. }
  648.